const utils = require("./utils");

app.extend = {
    all: [],
    serverApp: [],
    btnText: { 0: '已安装', 1: '需更新', 2: '需重装', 3: '下载' },
    btnTextColor: { 0: '#ffffff', 1: '#ff0000', 2: '#ff0000', 3: '#ff0000' },
    init: function () {
        log("init");
        this.all = app.getInstalledApps().map(function (item) {
            return item.packageName;
        });

        app.PATH = app.PATH || {}
        /*** 设置文件路径 ***/
        //app.C.G_A_TMP = files.join(app.C.G_A_TOP, 'tmp_dir');
        app.PATH.TMP = files.join('/storage/emulated/0/gdt', 'tmp_dir');
        files.ensureDir(app.PATH.TMP);
        app.PATH.APKS = files.join(app.PATH.TMP, 'apks');
        files.ensureDir(app.PATH.APKS);
    },
    getServerApp: function (localApps, cb) {

        

       // var normal_apps = ["抖音极速版", "快手极速版", "火山极速版", "趣头条", "转转", "快音", "秘乐短视频", "招财储蓄猫", "今日头条极速版", "番茄免费小说", "刷宝短视频", "火火视频极速版"];



      
        // let crab = [];
        //加载GDT
        let gdt = http.get("https://gitee.com/ttx/configs/raw/master/gdt/get_all_apk_info").body.json();
        let _app = {};
        let _serverApp = [];

        for (let index in gdt) {
            let item = gdt[index];
            item.type = 2;
            if(item.name){
                item.label = item.name;
            }
            _app[item.label] = item;
        }

        for (let item in _app) {
            _serverApp.push(_app[item]);
        }

        for (let index in _serverApp) {
            let item = _serverApp[index];
            item.checked = true;
            if (localApps.indexOf(item.pkg) !== -1) {
                //已经安装
               
                let localVersion = utils.getVersion(item.pkg);
                // log("item.version, localVersion", item.version, localVersion);
            
                let diff = utils.versionDiff(item.version, localVersion);
                switch (diff) {
                    case 1:
                        // 有更新
                        item.status = 1;
                        break;
                    case -1:
                        item.status = 2;
                        // 需重装
                        break;
                    default:
                        item.status = 0;
                        //正常
                        break;
                }

            } else {
                //未安装
                item.status = 3;
            }

        }

        // console.log("_serverApp", _serverApp)
        // this.serverApp = _serverApp;
        cb && cb(_serverApp);

    },
    exists: function (pkg) {
        return app.getAppName(pkg) != null;
    },
    getListButtonText: function (pkg) {
        if (this.all.indexOf(pkg) !== -1) {
            return "更新";
        } else {
            return "下载";
        }
    }
}
app.extend.init();